package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.TimeMarksCoverAdapter;
import com.github.postsanf.yinian.bean.TimeMarks;
import com.github.postsanf.yinian.bean.TimeMarksCoverBean;
import com.github.postsanf.yinian.bean.TimeMarksType;
import com.github.postsanf.yinian.bean.YNResponse;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.DateTimePickDialogUtil;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

public class CreatTimeMarksActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_title_bg;
    private TextView tv_time_type;
    private ImageView iv_title_bg_1;
    private EditText et_time_title;
    private ImageView iv_title_bg_2;
    private TextView tv_time_date;
    private ImageView iv_title_bg_3;
    private TextView tv_time_repetion;
    private ImageView iv_title_bg_4;
    private TextView tv_time_notify;
    private ImageView iv_title_bg_5;
    private ImageView iv_time_color;
    private TextView tv_birthday;
    private TextView tv_love;
    private TextView tv_memrial;
    private TextView tv_work;
    private TextView tv_test;
    private TextView tv_holiday;
    private TextView tv_weight;
    private TextView tv_honly;
    private TextView tv_other;
    private TextView tv_rpepety;
    private TextView tv_no_repety;
    private LinearLayout ll_one;
    private LinearLayout ll_two;
    private LinearLayout ll_week;
    private LinearLayout ll_no_notify;
    private ImageView iv_one;
    private ImageView iv_two;
    private ImageView iv_week;
    private ImageView iv_no_notify;
    private boolean oneSelecte;
    private boolean twoSelecte;
    private boolean weekSelecte;
    private boolean noNotifySelecte;
    private int num = 0;
    private TextView tv_choose_pic;
    private RecyclerView pic_recyclerview;
    private UploadManager mUpManager;
    private ImageView iv_bg;
    private TimeMarksCoverAdapter timeMarksCoverAdapter;
    private RecyclerView.LayoutManager layoutManager;
    private SimpleDraweeView sd_bg;
    private String notifyOne;
    private String notifyTwo;
    private String notifySeven;
    private String time = notifyTime(0);
    private int type;
    private String colorBg;
    private int repeat;
    private String picUrlBg;
    private String title;
    private String date;
    private ProgressDialog mProgressDialog;
    private String[] coverThem = new String[9];
    private String color = "#52d2ff,#f7d931,#f78a31,#ff525e,#46e0b3,#6436fd," +
            "#000000,#FFB6C1,#FFC0CB,#DC143C,#DB7093,#FF69B4,#FF1493,#C71585," +
            "#DA70D6,#D8BFD8,#DDA0DD,#EE82EE,#FF00FF,#8B008B,#800080,#BA55D3," +
            "#9400D3,#9932CC,#4B0082,#8A2BE2,#9370DB,#7B68EE,#6A5ACD,#483D8B," +
            "#0000FF,#0000CD,#191970,#00008B,#000080,#4169E1,#6495ED,#B0C4DE," +
            "#778899,#708090,#1E90FF,#4682B4,#87CEFA,#87CEEB,#00BFFF,#ADD8E6," +
            "#B0E0E6,#5F9EA0,#AFEEEE,#00FFFF,#00CED1,#2F4F4F,#008B8B,#008080," +
            "#48D1CC,#20B2AA,#40E0D0,#7FFFAA,#00FA9A,#00FF7F,#3CB371,#2E8B57," +
            "#90EE90,#98FB98,#8FBC8F,#32CD32,#00FF00,#228B22,#008000,#006400," +
            "#7FFF00,#7CFC00,#ADFF2F,#556B2F,#6B8E23,#FFFF00,#808000,#BDB76B," +
            "#FFFACD,#EEE8AA,#F0E68C,#FFD700,#DAA520,#F5DEB3,#FFE4B5,#FFA500," +
            "#FFEFD5,#FFEBCD,#FFDEAD,#D2B48C,#DEB887,#FFE4C4,#FF8C00,#CD853F," +
            "#FFDAB9,#F4A460,#D2691E,#8B4513,#A0522D,#FFA07A,#FF7F50,#FF4500," +
            "#E9967A,#FF6347,#FA8072,#F08080,#BC8F8F,#CD5C5C,#FF0000,#A52A2A," +
            "#B22222,#8B0000,#800000,#D3D3D3,#C0C0C0,#A9A9A9,#808080,#696969";
    private TextView creat_time_marks;
    private ImageView iv_back;
    private TimeMarks.DataBean edit;
    private DateTimePickDialogUtil dateTimePicKDialog;
    private RelativeLayout rl_time_repetion;
    private RelativeLayout rl_time_notify;
    private RelativeLayout rl_time_date;
    private LinearLayout ll_date;
    private LinearLayout ll_repetion;
    private LinearLayout ll_notify;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creat_time_marks);
        registerBroadcasr();
        mUpManager = application.getUploadManager();
        initView();
        getAllOfficialCovers();
        getType();
        initEdit();
    }

    private void initEdit() {
        Intent intent = getIntent();
        if (intent != null) {
            edit = (TimeMarks.DataBean) intent.getSerializableExtra("edit");
            if (edit != null) {
                tv_time_type.setText(edit.getMarkType());
                title = edit.getMarkContent();
                et_time_title.setText(edit.getMarkContent());
                date = edit.getMarkDate();
                tv_time_date.setText(edit.getMarkDate());
                dateTimePicKDialog = new DateTimePickDialogUtil(this, edit.getMarkDate());
                repeat = Integer.parseInt(edit.getMarkRepeat());
                if (edit.getMarkRepeat().equals("0")) {
                    tv_time_repetion.setText("不重复");
                } else {
                    tv_time_repetion.setText("重复");
                }
                String markNotify = edit.getMarkNotify();
                time = markNotify;
                String[] split = markNotify.split(",");
                if (split.length > 1) {
                    tv_time_notify.setText("重复提醒");
                } else if (split.length == 1 && !split[0].equals("")) {
                    tv_time_notify.setText(edit.getMarkNotify());
                } else {
                    tv_time_notify.setText("不提醒");
                }
                colorBg = edit.getMarkColor();
                iv_time_color.setBackgroundColor(Color.parseColor(edit.getMarkColor()));
                picUrlBg = edit.getMarkPic();
                ImageOptHelper.showFrescoSingeTimeCardCover(Uri.parse(edit.getMarkPic()), sd_bg, CreatTimeMarksActivity.this);
            }
        }
    }

    private void getType() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowTimeMarkTypes))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        TimeMarksType timeMarksType = gson.fromJson(s, TimeMarksType.class);
                        if (TextUtils.equals(timeMarksType.getMsg(), "success")) {
                            List<TimeMarksType.DataBean> data = timeMarksType.getData();
                            for (int i = 0; i < data.size(); i++) {
                                coverThem[i] = data.get(i).getOfficialCoverTheme();
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void initColor() {
        int i = (int) (Math.random() * 100);
        String[] colors = color.split(",");
        iv_time_color.setBackgroundColor(Color.parseColor(colors[i]));
        colorBg = colors[i];
    }

    private void initView() {
        iv_bg = ((ImageView) findViewById(R.id.iv_bg));
        iv_bg.setAlpha(0.5f);
        //点击空白区域隐藏键盘
        iv_bg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                iv_bg.setFocusable(true);
                iv_bg.setFocusableInTouchMode(true);
                iv_bg.requestFocus();
                InputMethodManager imm = (InputMethodManager) CreatTimeMarksActivity.this.getSystemService(CreatTimeMarksActivity.this.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                return false;
            }
        });
        iv_title_bg = ((ImageView) findViewById(R.id.iv_title_bg));
        iv_title_bg.setAlpha(0.6f);
        tv_time_type = ((TextView) findViewById(R.id.tv_time_type));

        iv_title_bg_1 = ((ImageView) findViewById(R.id.iv_title_bg_1));
        iv_title_bg_1.setAlpha(0.6f);
        et_time_title = ((EditText) findViewById(R.id.et_time_title));

        iv_title_bg_2 = ((ImageView) findViewById(R.id.iv_title_bg_2));
        iv_title_bg_2.setAlpha(0.6f);
        tv_time_date = ((TextView) findViewById(R.id.tv_time_date));
        tv_time_date.setText(notifyTime(0));
        dateTimePicKDialog = new DateTimePickDialogUtil(this, notifyTime(0));
        rl_time_date = ((RelativeLayout) findViewById(R.id.rl_time_date));
        ll_date = ((LinearLayout) findViewById(R.id.ll_date));
        ll_date.setOnClickListener(this);

        iv_title_bg_3 = ((ImageView) findViewById(R.id.iv_title_bg_3));
        iv_title_bg_3.setAlpha(0.6f);
        tv_time_repetion = ((TextView) findViewById(R.id.tv_time_repetion));
        rl_time_repetion = ((RelativeLayout) findViewById(R.id.rl_time_repetion));
        ll_repetion = ((LinearLayout) findViewById(R.id.ll_repetion));
        ll_repetion.setOnClickListener(this);

        iv_title_bg_4 = ((ImageView) findViewById(R.id.iv_title_bg_4));
        iv_title_bg_4.setAlpha(0.6f);
        tv_time_notify = ((TextView) findViewById(R.id.tv_time_notify));
        rl_time_notify = ((RelativeLayout) findViewById(R.id.rl_time_notify));
        ll_notify = ((LinearLayout) findViewById(R.id.ll_notify));
        ll_notify.setOnClickListener(this);

        iv_title_bg_5 = ((ImageView) findViewById(R.id.iv_title_bg_5));
        iv_title_bg_5.setAlpha(0.6f);
        iv_time_color = ((ImageView) findViewById(R.id.iv_time_color));

        tv_choose_pic = ((TextView) findViewById(R.id.tv_choose_pic));
        tv_choose_pic.setAlpha(0.5f);

        creat_time_marks = ((TextView) findViewById(R.id.creat_time_marks));
        sd_bg = ((SimpleDraweeView) findViewById(R.id.sd_bg));
        pic_recyclerview = ((RecyclerView) findViewById(R.id.pic_recyclerview));
        iv_back = ((ImageView) findViewById(R.id.iv_back));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        pic_recyclerview.setLayoutManager(linearLayoutManager);
        layoutManager = pic_recyclerview.getLayoutManager();
        tv_time_type.setOnClickListener(this);
        et_time_title.setOnClickListener(this);
        tv_time_date.setOnClickListener(this);
        tv_time_repetion.setOnClickListener(this);
        tv_time_notify.setOnClickListener(this);
        iv_time_color.setOnClickListener(this);
        creat_time_marks.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        initColor();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.tv_time_type:
                type = 3;
                showTypePopwindow();
                break;

            case R.id.et_time_title:
                break;

            case R.id.ll_date:
//                dateTimePicKDialog = new DateTimePickDialogUtil(this, notifyTime(0));
                dateTimePicKDialog.dateTimePicTimeMarksDialog(tv_time_date);
                break;

            case R.id.tv_time_date:
                dateTimePicKDialog.dateTimePicTimeMarksDialog(tv_time_date);
                break;

            case R.id.ll_repetion:
                showRepetionPopwindow();
                break;

            case R.id.tv_time_repetion:
                showRepetionPopwindow();
                break;

            case R.id.ll_notify:
                time = null;
                notifyOne = null;
                notifyTwo = null;
                notifySeven = null;
                shownotifyPopwindow();
                break;

            case R.id.tv_time_notify:
                time = null;
                notifyOne = null;
                notifyTwo = null;
                notifySeven = null;
                shownotifyPopwindow();
                break;

            case R.id.iv_time_color:
                startActivityForResult(new Intent(CreatTimeMarksActivity.this, TimeMarksColorActivity.class), 20);
                break;

            case R.id.ll_one:
                oneSelecte = !oneSelecte;
                String s1 = notifyTime(1);
                Log.d("yuhao", "notifyTime=" + s1);
                if (oneSelecte) {
                    num++;
                    iv_one.setImageResource(R.drawable.btn_select);
                    notifyOne = s1;
                } else {
                    if (num > 0) {
                        num--;
                    }
                    iv_one.setImageResource(R.drawable.btn_no_selecte);
                    notifyOne = null;
                }
                break;

            case R.id.ll_two:
                twoSelecte = !twoSelecte;
                String s2 = notifyTime(2);
                Log.d("yuhao", "notifyTime=" + s2);
                if (twoSelecte) {
                    num++;
                    iv_two.setImageResource(R.drawable.btn_select);
                    notifyTwo = s2;
                } else {
                    if (num > 0) {
                        num--;
                    }
                    iv_two.setImageResource(R.drawable.btn_no_selecte);
                    notifyTwo = null;
                }
                break;

            case R.id.ll_week:
                weekSelecte = !weekSelecte;
                String s7 = notifyTime(7);
                if (weekSelecte) {
                    num++;
                    iv_week.setImageResource(R.drawable.btn_select);
                    notifySeven = s7;
                } else {
                    if (num > 0) {
                        num--;
                    }
                    iv_week.setImageResource(R.drawable.btn_no_selecte);
                    notifySeven = null;
                }
                break;

            case R.id.ll_no_notify:
                noNotifySelecte = !noNotifySelecte;
                if (noNotifySelecte) {
                    num = 1;
                    iv_no_notify.setImageResource(R.drawable.btn_select);
                    iv_one.setImageResource(R.drawable.btn_no_selecte);
                    iv_two.setImageResource(R.drawable.btn_no_selecte);
                    iv_week.setImageResource(R.drawable.btn_no_selecte);
                    notifyOne = null;
                    notifyTwo = null;
                    notifySeven = null;
                } else {
                    num--;
                    iv_no_notify.setImageResource(R.drawable.btn_no_selecte);
                }
                break;

            case R.id.creat_time_marks:
                title = et_time_title.getText().toString().trim();
                date = tv_time_date.getText().toString().trim();
                if (picUrlBg != null && picUrlBg.startsWith("http://")) {
                    if (edit == null) {
                        addTimeMarks();
                    } else {
                        modifyTimeMarks();
                    }
                } else {
                    getToken();
                }
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mProgressDialog.dismiss();
                    }
                }, 1000 * 60);
                break;
        }
    }

    private void getToken() {
        mProgressDialog = ProgressDialog.show(CreatTimeMarksActivity.this, "", "");
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            uploadToqiniu();
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        //  showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void uploadToqiniu() {
        final File uploadFile = new File(picUrlBg);
        UploadOptions uploadOptions = new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {

                    }
                }, new UpCancellationSignal() {
            @Override
            public boolean isCancelled() {
                return false;
            }
        });
        String prefix = picUrlBg.substring(picUrlBg.lastIndexOf(".") + 1);
        // 为图片重命名
        String imgName = UUID.randomUUID().toString() + "." + prefix;
        mUpManager.put(uploadFile, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo respInfo, JSONObject jsonData) {
                        if (respInfo.isOK()) {
                            try {
                                picUrlBg = "http://7xlmtr.com1.z0.glb.clouddn.com/" + jsonData.getString("key");
                                if (edit == null) {
                                    addTimeMarks();
                                } else {
                                    modifyTimeMarks();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            showLog("----------------------------七牛云上传图片失败---------------------------------");
                        }
                    }
                }, uploadOptions);
    }

    private void addTimeMarks() {
        if (picUrlBg.startsWith("http://")) {
            mProgressDialog = ProgressDialog.show(CreatTimeMarksActivity.this, "", "");
        }
        final String typeThem = tv_time_type.getText().toString().trim();
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_TYPE, typeThem);
        mParam.put(CommonConstants.CONTENT, title);
        mParam.put(CommonConstants.DATE, date);
        mParam.put(CommonConstants.COLOR, colorBg);
        mParam.put(CommonConstants.PICTURE, picUrlBg);
        mParam.put(CommonConstants.REPEAT, String.valueOf(repeat));
        mParam.put(CommonConstants.NOTIFY, time);
//        Log.d("yuhao", "type="+typeThem);
//        Log.d("yuhao", "userid="+application.getCurID());
//        Log.d("yuhao", "groupid="+application.getCurGid());
//        Log.d("yuhao", "picUrl="+picUrlBg);
//        Log.d("yuhao", "colorBg="+colorBg);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynAddTimeMark))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNResponse ynResponse = gson.fromJson(s, YNResponse.class);
                        if (TextUtils.equals(ynResponse.getMsg(), "success")) {
                            showToast("创建成功");
//                            List<TimeMarks.DataBean> modifyTimeMarks=new ArrayList<>();
//                            TimeMarks.DataBean dataBean = new TimeMarks.DataBean();
//                            modifyTimeMarks.add(dataBean);
//                            modifyTimeMarks.get(0).setUserid(String.valueOf(application.getCurID()));
//                            modifyTimeMarks.get(0).setMarkType(typeThem);
//                            modifyTimeMarks.get(0).setMarkContent(title);
//                            modifyTimeMarks.get(0).setMarkDate(date);
//                            modifyTimeMarks.get(0).setMarkColor(colorBg);
//                            modifyTimeMarks.get(0).setMarkPic(picUrlBg);
//                            modifyTimeMarks.get(0).setMarkRepeat(String.valueOf(repeat));
//                            modifyTimeMarks.get(0).setMarkNotify(time);
//                            modifyTimeMarks.get(0).setMarkID(edit.getMarkID());
                            Intent intent = new Intent(ACTIONs.TimeMarks);
//                            intent.putExtra("addTimeMarks",(Serializable) modifyTimeMarks);
                            intent.putExtra("position", 0);
                            sendBroadcast(intent);
                            finish();
                        }
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void modifyTimeMarks() {
        if (picUrlBg.startsWith("http://")) {
            mProgressDialog = ProgressDialog.show(CreatTimeMarksActivity.this, "", "");
        }
        final String typeThem = tv_time_type.getText().toString().trim();
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.MARKID, edit.getMarkID());
        mParam.put(CommonConstants.YNS_TYPE, typeThem);
        mParam.put(CommonConstants.CONTENT, title);
        mParam.put(CommonConstants.DATE, date);
        mParam.put(CommonConstants.COLOR, colorBg);
        mParam.put(CommonConstants.PICTURE, picUrlBg);
        mParam.put(CommonConstants.REPEAT, String.valueOf(repeat));
        mParam.put(CommonConstants.NOTIFY, time);
//        Log.d("yuhao", "type="+typeThem);
//        Log.d("yuhao", "MarkID="+edit.getMarkID());
//        Log.d("yuhao", "title="+title);
//        Log.d("yuhao", "date="+date);
//        Log.d("yuhao", "repeat="+repeat);
//        Log.d("yuhao", "time="+time);
//        Log.d("yuhao", "picUrl="+picUrlBg);
//        Log.d("yuhao", "colorBg="+colorBg);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynModifyTimeMark))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNResponse ynResponse = gson.fromJson(s, YNResponse.class);
                        if (TextUtils.equals(ynResponse.getMsg(), "success")) {
                            showToast("修改成功");
                            List<TimeMarks.DataBean> modifyTimeMarks = new ArrayList<>();
                            TimeMarks.DataBean dataBean = new TimeMarks.DataBean();
                            modifyTimeMarks.add(dataBean);
                            modifyTimeMarks.get(0).setUserid(String.valueOf(application.getCurID()));
                            modifyTimeMarks.get(0).setMarkType(typeThem);
                            modifyTimeMarks.get(0).setMarkContent(title);
                            modifyTimeMarks.get(0).setMarkDate(date);
                            modifyTimeMarks.get(0).setMarkColor(colorBg);
                            modifyTimeMarks.get(0).setMarkPic(picUrlBg);
                            modifyTimeMarks.get(0).setMarkRepeat(String.valueOf(repeat));
                            modifyTimeMarks.get(0).setMarkNotify(time);
                            modifyTimeMarks.get(0).setMarkID(edit.getMarkID());
                            Intent intent = new Intent(ACTIONs.ModifyTimeMarks);
                            intent.putExtra("modifyTimeMarks", (Serializable) modifyTimeMarks);
                            intent.putExtra("position", 0);
                            sendBroadcast(intent);
                            finish();
                        }
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    //类型
    private void showTypePopwindow() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(CreatTimeMarksActivity.this).inflate(
                R.layout.popwindow_time_type, null);

        tv_birthday = ((TextView) contentView.findViewById(R.id.tv_birthday));
        tv_love = ((TextView) contentView.findViewById(R.id.tv_love));
        tv_memrial = (TextView) contentView.findViewById(R.id.tv_memrial);
        tv_work = ((TextView) contentView.findViewById(R.id.tv_work));
        tv_test = ((TextView) contentView.findViewById(R.id.tv_test));
        tv_holiday = ((TextView) contentView.findViewById(R.id.tv_holiday));
        tv_weight = ((TextView) contentView.findViewById(R.id.tv_weight));
        tv_honly = ((TextView) contentView.findViewById(R.id.tv_honly));
        tv_other = ((TextView) contentView.findViewById(R.id.tv_other));

        ImageView iv_type_bg = (ImageView) contentView.findViewById(R.id.iv_type_bg);
        iv_type_bg.setAlpha(0.8f);

        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);
        tv_birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[0]);
                type = 1;
                popupWindow.dismiss();
            }
        });
        tv_love.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[1]);
                type = 2;
                popupWindow.dismiss();
            }
        });
        tv_memrial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[2]);
                type = 3;
                popupWindow.dismiss();
            }
        });
        tv_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[3]);
                type = 4;
                popupWindow.dismiss();
            }
        });
        tv_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[4]);
                type = 5;
                popupWindow.dismiss();
            }
        });
        tv_holiday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[5]);
                type = 6;
                popupWindow.dismiss();
            }
        });
        tv_weight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[6]);
                type = 7;
                popupWindow.dismiss();
            }
        });
        tv_honly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[7]);
                type = 8;
                popupWindow.dismiss();
            }
        });
        tv_other.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_type.setText(coverThem[8]);
                type = 9;
                popupWindow.dismiss();
            }
        });
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;

            }
        });

        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.bg_type));
        popupWindow.showAtLocation(contentView, Gravity.NO_GRAVITY, UIHelper.dip2px(CreatTimeMarksActivity.this, 42 + 60), UIHelper.dip2px(CreatTimeMarksActivity.this, 58));
//        popupWindow.showAsDropDown(contentView);
    }


    //重复
    private void showRepetionPopwindow() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(CreatTimeMarksActivity.this).inflate(
                R.layout.popwindow_time_repetion, null);

        ImageView iv_type_bg = (ImageView) contentView.findViewById(R.id.iv_type_bg);
        iv_type_bg.setAlpha(0.8f);

        tv_rpepety = ((TextView) contentView.findViewById(R.id.tv_rpepety));
        tv_no_repety = ((TextView) contentView.findViewById(R.id.tv_no_repety));

        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        tv_rpepety.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_repetion.setText("重复");
                repeat = 1;
                popupWindow.dismiss();
            }
        });

        tv_no_repety.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time_repetion.setText("不重复");
                repeat = 0;
                popupWindow.dismiss();
            }
        });

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;

            }
        });

        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.bg_repetion));
        popupWindow.showAtLocation(contentView, Gravity.NO_GRAVITY, UIHelper.dip2px(CreatTimeMarksActivity.this, 42 + 60), UIHelper.dip2px(CreatTimeMarksActivity.this, 214));
//        popupWindow.showAsDropDown(contentView);
    }

    //提醒
    private void shownotifyPopwindow() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(CreatTimeMarksActivity.this).inflate(
                R.layout.popwindow_time_notify, null);

        ImageView iv_type_bg = (ImageView) contentView.findViewById(R.id.iv_type_bg);
        iv_type_bg.setAlpha(0.8f);

        ll_one = ((LinearLayout) contentView.findViewById(R.id.ll_one));
        iv_one = ((ImageView) contentView.findViewById(R.id.iv_one));
        ll_two = ((LinearLayout) contentView.findViewById(R.id.ll_two));
        iv_two = ((ImageView) contentView.findViewById(R.id.iv_two));
        ll_week = ((LinearLayout) contentView.findViewById(R.id.ll_week));
        iv_week = ((ImageView) contentView.findViewById(R.id.iv_week));
        ll_no_notify = ((LinearLayout) contentView.findViewById(R.id.ll_no_notify));
        iv_no_notify = ((ImageView) contentView.findViewById(R.id.iv_no_notify));

        ll_one.setOnClickListener(this);
        ll_two.setOnClickListener(this);
        ll_week.setOnClickListener(this);
        ll_no_notify.setOnClickListener(this);
        iv_one.setOnClickListener(this);
        iv_two.setOnClickListener(this);
        iv_week.setOnClickListener(this);
        iv_no_notify.setOnClickListener(this);

        final PopupWindow notifyPopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        notifyPopupWindow.setTouchable(true);

        notifyPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (num > 1) {
                    tv_time_notify.setText("重复提醒");
                    if (notifyOne == null) {
                        time = "," + notifyTwo + "," + notifySeven;
                    } else if (notifyTwo == null) {
                        time = notifyOne + "," + notifySeven;
                    } else if (notifySeven == null) {
                        time = notifyOne + "," + notifyTwo;
                    } else {
                        time = notifyOne + "," + notifyTwo + "," + notifySeven;
                    }
                } else if (num == 0) {
//                    tv_time_notify.setText("当天提醒");
                    time = notifyTime(0);
                }
                if (num == 1) {
                    if (oneSelecte) {
                        tv_time_notify.setText("提前一天提醒");
                        time = notifyTime(1);
                    } else if (twoSelecte) {
                        tv_time_notify.setText("提前两天提醒");
                        time = notifyTime(2);
                    } else if (weekSelecte) {
                        tv_time_notify.setText("提前一周提醒");
                        time = notifyTime(7);
                    } else if (noNotifySelecte) {
                        tv_time_notify.setText("不提醒");
                        time = "";
                    }
                }
//                Log.d("yuhao", "oneSelecte+twoSelecte+weekSelecte="+oneSelecte+twoSelecte+weekSelecte);
                oneSelecte = false;
                twoSelecte = false;
                weekSelecte = false;
                noNotifySelecte = false;
                num = 0;
//                Log.d("yuhao", "time="+time);
            }
        });

        notifyPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;

            }
        });

        notifyPopupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.bg_repetion));
        notifyPopupWindow.showAtLocation(contentView, Gravity.NO_GRAVITY, UIHelper.dip2px(CreatTimeMarksActivity.this, 42 + 60), UIHelper.dip2px(CreatTimeMarksActivity.this, 266));
//        popupWindow.showAsDropDown(contentView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_ALBUM:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }

                Uri imageUri = data.getData();
                picUrlBg = ImageUtils.getImageAbsolutePath19(CreatTimeMarksActivity.this, imageUri);
                ImageOptHelper.showFrescoTimeMarks(imageUri, sd_bg, CreatTimeMarksActivity.this);
                break;
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
                    picUrlBg = ImageUtils.getImageAbsolutePath19(CreatTimeMarksActivity.this, imageUriCamera);
                    ImageOptHelper.showFrescoTimeMarks(imageUriCamera, sd_bg, CreatTimeMarksActivity.this);
                }
                break;

            case 20:
                if (data != null) {
                    colorBg = data.getStringExtra("colors");
                }
                iv_time_color.setBackgroundColor(Color.parseColor(colorBg));
                break;
            default:
                break;
        }
//        if (resultCode==RESULT_OK&&data!=null){
//            String colors = data.getStringExtra("colors");
//            iv_time_color.setBackgroundColor(Color.parseColor(colors));
//        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getAllOfficialCovers() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowTimeMarkBackgroundPic))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        TimeMarksCoverBean timeMarksCoverBean = gson.fromJson(s, TimeMarksCoverBean.class);
                        if (TextUtils.equals(timeMarksCoverBean.getMsg(), "success")) {
                            List<TimeMarksCoverBean.DataBean> data = timeMarksCoverBean.getData();
                            timeMarksCoverAdapter = new TimeMarksCoverAdapter(CreatTimeMarksActivity.this, data);
                            pic_recyclerview.setAdapter(timeMarksCoverAdapter);
//                            ImageLoader.getInstance().displayImage(data.get(0).getOfficialCoverPicture(),iv_time_marks_bg);
                            if (edit == null) {
                                picUrlBg = data.get(0).getOfficialCoverPicture();
                                ImageOptHelper.showFrescoSingeTimeCardCover(Uri.parse(data.get(0).getOfficialCoverPicture()), sd_bg, CreatTimeMarksActivity.this);
                            }
                            changeBg();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void changeBg() {
        timeMarksCoverAdapter.setOnPicChangeListener(new TimeMarksCoverAdapter.OnPicChangeListener() {
            @Override
            public void setOnPicChangeListener(String url, int position) {
//                iv_time_marks_bg.setVisibility(View.VISIBLE);
//                sd_bg.setVisibility(View.GONE);
//                ImageLoader.getInstance().displayImage(url,iv_time_marks_bg);
                picUrlBg = url;
                ImageOptHelper.showFrescoSingeTimeCardCover(Uri.parse(url), sd_bg, CreatTimeMarksActivity.this);
                timeMarksCoverAdapter.notifyDataSetChanged();
//                ((LinearLayoutManager)layoutManager).scrollToPositionWithOffset(positionOld, top);
            }
        });
    }


    private void registerBroadcasr() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.Selected);
        registerReceiver(MyReceiver, myIntentFilter);
    }

    BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTIONs.Selected)) {
                String selected = intent.getStringExtra("selected");
                picUrlBg = selected;
                ImageOptHelper.showFrescoSingeTimeCardCover(Uri.parse(selected), sd_bg, CreatTimeMarksActivity.this);
            }
        }
    };

    public String notifyTime(int i) {
        long currentMillis = System.currentTimeMillis();
        long notityTimeMillis = currentMillis - 3600 * 1000 * 24 * i;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(notityTimeMillis);//获取提醒时间
        String notifyTime = formatter.format(curDate);
        return notifyTime;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(MyReceiver);
        super.onDestroy();
    }

    //友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
